package com.ray.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.UUID;

import org.joda.time.DateTime;
import org.joda.time.Interval;
import org.joda.time.Period;

import com.google.appengine.api.memcache.MemcacheServicePb.MemcacheSetResponse.SetStatusCode;

public class TimeAndUnix {

	// 将时间戳转换为时间
	public static String TimeStamp2Date(String timestampString, String formats) {
		if (null == formats || "".equals(formats)) {
			formats = "yyyy-MM-dd HH:mm:ss";
		}
		Long timestamp = Long.parseLong(timestampString) * 1000;
		String date = new SimpleDateFormat(formats, Locale.CHINA).format(new Date(timestamp));
		return date;
	}

	// 将时间转换为时间戳
	public static String Date2TimeStamp(String dateStr, String format) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat(format);
			return String.valueOf(sdf.parse(dateStr).getTime() / 1000);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	// 获取当前时间时间戳
	public static String getNowTimeStamp() {
		long time = System.currentTimeMillis();
		String nowTimeStamp = String.valueOf(time / 1000);
		return nowTimeStamp;
	}

	// 获取隔几天日期加时间，时间为参数
	public static String getBeforeDay(int day, String fomart) {
		Date dNow = new Date(); // 当前时间
		Date dBefore = new Date();
		Calendar calendar = Calendar.getInstance(); // 得到日历
		calendar.setTime(dNow);// 把当前时间赋给日历
		calendar.add(Calendar.DAY_OF_MONTH, day); // 设置为前一天
		dBefore = calendar.getTime(); // 得到前一天的时间
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 设置时间格式
		String defaultStartDate = sdf.format(dBefore); // 格式化前一天
		return defaultStartDate + fomart;
	}

	// 生成随机字符串
	public static String create_nonce_str() {
		return UUID.randomUUID().toString();
	}

	// 获取日期相隔天数
	public static int getDateDays(String startDate, String endDate) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date1 = sdf.parse(startDate);
		Date date2 = sdf.parse(endDate);
		return getDateDays(date1, date2);
	}

	public static int getDateDays(Date early, Date late) {
		Calendar calst = Calendar.getInstance();
		Calendar caled = Calendar.getInstance();
		calst.setTime(early);
		caled.setTime(late);
		// 设置时间为0时
		calst.set(java.util.Calendar.HOUR_OF_DAY, 0);
		calst.set(java.util.Calendar.MINUTE, 0);
		calst.set(java.util.Calendar.SECOND, 0);
		caled.set(java.util.Calendar.HOUR_OF_DAY, 0);
		caled.set(java.util.Calendar.MINUTE, 0);
		caled.set(java.util.Calendar.SECOND, 0);
		// 得到两个日期相差的天数
		int days = ((int) (caled.getTime().getTime() / 1000) - (int) (calst.getTime().getTime() / 1000)) / 3600 / 24;

		return days;
	}

	public static String timeAddDay(String timeString, int add) throws ParseException {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date date = sdf.parse(timeString);
		String xx = sdf.format(date);
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		calendar.add(Calendar.DAY_OF_MONTH, add);
		Date date1 = calendar.getTime();
		return sdf.format(date1);
	}
	
	public static Long time2number(String timeStr,String format) {
		if (format == null || format == "") {
			format = "yyyy-MM-dd HH:mm:ss.S";
		}
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		Long time;
		try {
			time = sdf.parse(timeStr).getTime();
		} catch (ParseException e) {
			e.printStackTrace();
			time = null;
		}
		return time;
	}
	
	//时间字符串转毫秒
	public static String timeToHaoMiao(String strTime) throws ParseException {
		if(strTime==null || "".equals(strTime)) {
			return null;
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		Date date = sdf.parse(strTime);
		return date.getTime()+"";
	}
	
	//毫秒字符串转时间字符串
    public static String haoMiaoToTime(String haoMiao) {
    	if(haoMiao == null || "".equals(haoMiao)) {
    		return null;
    	}
    	Long purchaseTime = Long.parseLong(haoMiao);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss:SSS");
    	return  sdf.format(new Date(purchaseTime));
    }
    
    /**
     * 给指定日期加上天数
    * @date 2018年5月28日 上午7:49:21 
    * @author 李斌
    * @return String 
    * @throws
     */
    public static String plusDay(int num,String newDate) throws ParseException{
        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		Date  currdate = format.parse(newDate);
		Calendar ca = Calendar.getInstance(); 
		ca.add(Calendar.DATE, num);// num为增加的天数，可以改变的
		currdate = ca.getTime();
		String enddate = format.format(currdate);
		return enddate;
    }
    
    
    /**
     * 获取今天的日期或者昨天的日期
     * @return
     * @throws ParseException
     */
    public static  String isToDayOrLastDay() throws ParseException {
    	SimpleDateFormat daysdf=new SimpleDateFormat("yyyy-MM-dd");
    	SimpleDateFormat sdf=new SimpleDateFormat("HH:mm:ss");
		String xx=sdf.format(new Date());
		System.out.println(xx);
		DateFormat df = new SimpleDateFormat("HH:mm:ss");//创建日期转换对象HH:mm:ss为时分秒，年月日为yyyy-MM-dd  
        Date dt1 = df.parse(xx);//将字符串转换为date类型  
        Date dt2 = df.parse("12:00:00");  
        if(dt1.getTime()>dt2.getTime()) {  //比较时间大小,如果大于12点  返回今天日期
            return  daysdf.format(new Date());
        }else {  
            return TimeAndUnix.getBeforeDay(-1, "");
        }  
    }
    /**
     * 比较两个时间字符串，返回相差毫秒数
     * @param startTime
     * @param endTime
     * @return 两个日期相差毫秒数
     * @author 王荣
     */
    public static double compareDate(String startTime,String endTime) {
    	SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	try {
			Date d1 = sdf.parse(startTime);
			Date d2 = sdf.parse(endTime);
			return d2.getTime()-d1.getTime();
		} catch (ParseException e) {
			e.printStackTrace();
		}
    	return 0;
    }
    /**
     * 比较两个日期相差毫秒数，根据指定的日期解析格式
     * @param startTime
     * @param startTimeFormat 开始时间格式
     * @param endTime
     * @param endTimeFormat 结束时间格式
     * @return 两个日期相差的毫秒数
     * @author 王荣
     */
    public static long compareDate(String startTime,String startTimeFormat,String endTime,String endTimeFormat) {
    	startTimeFormat = startTimeFormat==null?"yyyy-MM-dd HH:mm:ss":startTimeFormat;
    	endTimeFormat = endTimeFormat==null?"yyyy-MM-dd HH:mm:ss":endTimeFormat;
    	SimpleDateFormat sdf1=new SimpleDateFormat(startTimeFormat);
    	SimpleDateFormat sdf2=new SimpleDateFormat(endTimeFormat);
    	try {
			Date d1 = sdf1.parse(startTime);
			Date d2 = sdf2.parse(endTime);
			return d2.getTime()-d1.getTime();
		} catch (ParseException e) {
			e.printStackTrace();
		}
    	return 0;
    }
    /**
     * 比较两个日期相差毫秒数，根据指定的日期解析格式
     * @param startTime
     * @param startTimeFormat {@code SimpleDateFormat}
     * @param endTime
     * @param endTimeFormat {@code SimpleDateFormat}
     * @return 两个日期相差的毫秒数
     * @author 王荣
     */
    public static long compareDate(String startTime,SimpleDateFormat startTimeFormat,String endTime,SimpleDateFormat endTimeFormat) {
    	try {
			Date d1 = startTimeFormat.parse(startTime);
			Date d2 = endTimeFormat.parse(endTime);
			return d2.getTime()-d1.getTime();
		} catch (ParseException e) {
			e.printStackTrace();
		}
    	return 0;
    }
    /**
     * 比较两个DateTime时间相差的分钟数
     * @param startTime
     * @param endTime
     * @return endTime-startTime相差的分钟数
     * @author 王荣
     */
    public static int compareDate(DateTime startTime,DateTime endTime) {
    	Interval interval = new Interval(startTime,endTime);
		Period period = interval.toPeriod();
		return period.getDays()*24*60+period.getHours()*60+period.getMinutes();
    }
    /**
     * @param startTime
     * @param endTime
     * @return 两个DateTime时间相差的小时数（double）
     * @author 王荣
     */
    public static double compareDateWithHour(DateTime startTime,DateTime endTime) {
    	Interval interval = new Interval(startTime,endTime);
		Period period = interval.toPeriod();
		return period.getHours()+(double)(period.getMinutes())/60;
    }
    /**
     * 转换时间字符串为毫秒
     * @param time
     * @return 时间戳（毫秒）
     * @author 王荣
     */
    public static long convertTime2stamp(String time) {
    	if(time==null || "".equals(time)) return 0;
		try {
			return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(time).getTime();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return 0;
    }
    
    /**
     * 
     * @Title: compTime  
     * @author: 李宇航 
     * @Description: 给出两个时间类型字符串形如22：12：14若time1>=time2返回true否则返回false
     * @param time1
     * @param time2     
     * @return: boolean      
     * @throws
     */
    public static boolean compTime(String time1,String time2){
		try {
			if (time1.indexOf(":")<0||time2.indexOf(":")<0) {
				System.out.println("格式不正确");
			}else{
				String[]array1 = time1.split(":");
				int total1 = Integer.valueOf(array1[0])*3600+Integer.valueOf(array1[1])*60+Integer.valueOf(array1[2]);
				String[]array2 = time2.split(":");
				int total2 = Integer.valueOf(array2[0])*3600+Integer.valueOf(array2[1])*60+Integer.valueOf(array2[2]);
				return total1-total2>=0;
			}
		} catch (NumberFormatException e) {
			return false;
		}
		return false;
 
	}
    
    /**
     * 获取日期加减几个月的日期
     * @param date
     * @return
     * @throws ParseException
     */
    public static   String subMonth(String date,int  subCount) throws ParseException {  
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
        Date dt = sdf.parse(date);  
        Calendar rightNow = Calendar.getInstance();  
        rightNow.setTime(dt);  
        rightNow.add(Calendar.MONTH, subCount);  
        Date dt1 = rightNow.getTime();  
        String reStr = sdf.format(dt1);  
        return reStr;  
    }
    
    public static Date getmindate(){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
        return calendar.getTime();
    }

    /**
     * 获取本月最后一天
     * @return
     */
    public static Date getmaxdate(){
        Calendar calendar2 = Calendar.getInstance();
        calendar2.setTime(new Date());
        calendar2.set(Calendar.DAY_OF_MONTH, calendar2.getActualMaximum(Calendar.DAY_OF_MONTH));
        return calendar2.getTime();
    }
    
}
